import backtrader as bt
import numpy as np
import numpy as np
import pandas as pd
#波动率
class wave_index_ind (bt.Indicator):
    lines = ('wave',)
    def __init__(self, wave_window,data):
        self.params.wave_window = wave_window
        value_list = data.get(ago = data.buflen(), size = data.buflen())
        self.wave_value = self.getwave( value_list)
        # 这个很有用，会有 not maturity生成  设置了开始的位置
        # self.addminperiod(self.params.wave_window * 2)

    def getwave(self,value_list):
        stockdata = pd.DataFrame(value_list, columns=['close'])
        wave = []
        df_close = stockdata.close / stockdata.close[0]
        for i in range(0, len(stockdata.index)):
            if i > self.p.wave_window:
                wave.append(np.std(np.log(df_close[i - self.p.wave_window:i] / df_close[i - self.p.wave_window:i].shift(-1))) * np.sqrt(252) * 100)
            else:
                wave.append(0)
        return wave

    def next(self):
       try:
        num =len(self.wave)#当前位置
        self.lines.wave[0] = self.wave_value[num-1]
       except Exception as e:
        1 + 1